package main

import (
    "github.com/go-gomail/gomail"
    "log"
    "github.com/Unknwon/goconfig"
    "flag"
    "strconv"
    "fmt"
)



func sendmail(from,to,from_name,to_name,subject,body,smtpserver,passwd string , port int) error {
    m := gomail.NewMessage()
    m.SetAddressHeader("From", from, from_name)
    m.SetHeader("To",
        m.FormatAddress(to, to_name),
    )
    m.SetHeader("Subject", subject)
    m.SetBody("text/html", body)

    d := gomail.NewPlainDialer(smtpserver, port, from, passwd)
    if err := d.DialAndSend(m); err != nil {
        return err
        }
        return nil
}

func main() {
    config_path := flag.String("c","./send_config.ini","发件配置信息")
    to_addr := flag.String("t","xxxx@qq.com","收件人邮箱")
    subject := flag.String("p","主题","指定邮件主题")
    body := flag.String("b","正文","邮件正文")

    cfg, err := goconfig.LoadConfigFile(*config_path)
    if err != nil {
        log.Println("读取配置文件失败:", *config_path)
        return
    }
    from_addr, _ := cfg.GetValue(goconfig.DEFAULT_SECTION, "from_address")  //发件人邮箱
    from_name, _ := cfg.GetValue(goconfig.DEFAULT_SECTION, "from_name")   //发件人姓名
    to_name, _ := cfg.GetValue(goconfig.DEFAULT_SECTION, "to_name")   //收件人姓名
    smtp_server, _ := cfg.GetValue(goconfig.DEFAULT_SECTION, "smtp_server") //smtp服务器地址
    passwd,_ := cfg.GetValue(goconfig.DEFAULT_SECTION, "password") //密码
    PORT,_ := cfg.GetValue(goconfig.DEFAULT_SECTION, "port") //smtp端口
    port, err2 := strconv.Atoi(PORT)
    if err2 != nil {
        log.Println(err2)
    }

    err1 := sendmail(from_addr,*to_addr,from_name,to_name,*subject,*body,smtp_server,passwd,port)
    if err1 != nil {
        log.Println(err1)
    }

    fmt.Println(from_addr,from_name,to_name,smtp_server,passwd,port)


}
